package cn.lvhang.user.service.impl;

import cn.lvhang.basic.exception.BusinessException;
import cn.lvhang.basic.util.SmsUtils;
import cn.lvhang.basic.util.StrUtils;
import cn.lvhang.user.constant.UserConstants;
import cn.lvhang.user.domain.User;
import cn.lvhang.user.mapper.UserMapper;
import cn.lvhang.user.service.IVerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void smsCode(Map<String,String> param) {
        String phone = param.get("phone");
        String type = param.get("type");
        //1.校验
        //1.1 手机号不能为空
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(type) ){
            throw new BusinessException("参数不能为空！");
        }
        String businessKey = "";
        if("register".equals(type)){
            //1.2 手机号是否被注册
            User user = userMapper.loadByPhone(phone);
            if(user != null){
                throw new BusinessException("该号码已经被注册，请直接登录！");
            }
            businessKey =  UserConstants.BUSINESS_REGISTER_PREFIX + phone;
        }else if("binder".equals(type)){
            businessKey =  UserConstants.BUSINESS_BINDER_PREFIX + phone;
        }
        if(StringUtils.hasLength(businessKey)){
            sendCode(businessKey);
        }
    }

    //发送验证码
    public void sendCode(String businessKey){
        //2.判断验证码是否有效（3分钟），从redis中是否能拿到 key
        Object codeTmp = redisTemplate.opsForValue()
                .get(businessKey);
        String code = "";
        if(codeTmp != null){
            //2.1 如果拿到了 需要判断是否过了1分钟重发时间
            String timeTmp = codeTmp.toString().split(":")[1];
            if(System.currentTimeMillis()-Long.valueOf(timeTmp) <= 1*60*1000){
                //2.1.1 如果没有过重发时间,报错：请勿重发获取验证码
                throw new BusinessException("请勿重复获取验证码！！！");
            }else{
                //2.2 如果过了重发时间，使用上次的验证码
                code = codeTmp.toString().split(":")[0];
            }
        }else{
            //2.3如果拿不到直接生成新的验证码
            code = StrUtils.getComplexRandomString(4);
        }
        //3.存储redis 设置3分钟过期
        redisTemplate.opsForValue().set(
                businessKey,
                code+":"+System.currentTimeMillis(),
                3,
                TimeUnit.MINUTES);

        //4.发送短信通知用户
        //SmsUtils.send(phone, "您的验证是："+code+";请在三分钟内使用！");
        System.out.println("您的验证是：" + code + ";请在三分钟内使用！");
    }
}